package com.imooc.security.core.validate.code;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * 验证码请求Controller
 * @author Jon
 *
 */
@RestController
public class ValidateController {
	
	public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
	
	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();//session缓存对象
	
	@Autowired
	private ValidateCodeGenerator imageCodeGenerator;
	
	
	/**   
	 * Description  		生成图形验证码
	 * 备注，图形验证码有三个可配置项，分别是：
	 * 	1.图形验证码的高、宽、字符长度和过期时间
	 * 	2.需要被图形验证码验证的url地址集合
	 * 	3.生成图形验证码的代码逻辑
	 */ 
	@GetMapping("/code/image")
	public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//1.生成图片验证码对象
		ImageCode imageCode = imageCodeGenerator.createImageCode(request);
		//2.将对象存入session缓存中
		sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
		//3.将生成的图片写到响应中
		ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
	}
}
